package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;

import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    //    @Autowired
//    private IDepartmentService departmentService;
    @Autowired
    private IPermissionService permissionService;

    //处理查询所有部门请求
    @RequiredPermission(name = "角色页面", expression = "role:list")
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo) {
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
//        List<Department> departments = departmentService.listAll();
//        model.addAttribute("departments", departments);
        return "role/list";//找视图,/WEB-INF/views/role/list.jsp
    }

    //处理删除请求
    @RequiredPermission(name = "角色删除", expression = "role:delete")
    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            roleService.delete(id);
        }
        return "redirect:/role/list";//让浏览器重新发一次请求
    }

    //去新增或去修改页面
    @RequiredPermission(name = "角色新增/编辑", expression = "role:saveOrUpdate")
    @RequestMapping("/input")
    public String input(Long id, Model model) {
//        List<Department> departments = departmentService.listAll();
//        //查询所有数据往模型中存入,提供数据,让员工新增修改时显示出来让角色选择
//        model.addAttribute("departments", departments);
        List<Role> roles = roleService.selectAll();
        model.addAttribute("roles", roles);
        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("permissions",permissions);
        if (id != null) {
            List<Permission> rolePermission = permissionService.selectByRoleId(id);
            model.addAttribute("rolePermission",rolePermission);
            Role role = roleService.selectOne(id);
            model.addAttribute("role", role);
        }
        return "role/input";//让浏览器再发一次请求
    }

    @RequiredPermission(name = "角色新增/编辑", expression = "role:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role, Long[] ids) {
        if (role.getId() == null) {
            roleService.insert(role, ids);//新增
        } else {
            roleService.update(role, ids);//修改
        }
        return "redirect:/role/list";
    }
}
